package com.epro.dx.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.baifendian.mobile.BfdAgent;
import android.widget.TextView;

import com.epro.dx.R;
import com.epro.dx.listenner.MyAsyncTaskListenner;
import com.epro.dx.task.GetIsNotReadAsyncTask;
import com.epro.dx.task.GetOneKeyFilterSettingsAsyncTask;
import com.epro.dx.task.GetTopCategoryAsyncTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.GlobalConfig;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.UserModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.GlobalConfig.UserSessionCfg;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;
import java.util.HashMap;

/**
 * 注册
 *
 * @author Administrator
 * @version [版本号, 2010-8-30]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */

public class RegisterActivity extends BaseFragmentActivity implements OnClickListener, OnFocusChangeListener {
    private static final String TAG = RegisterActivity.class.getSimpleName();

    private String email;

    private String username;

    private String firstname;

    private String lastname;

    private String password;

    private String passwordConfirm;

    /**
     * 输入法管理器
     */
    InputMethodManager localInputMethodManager;

    private RelativeLayout submit;

    private UserModel userModel;

    private Tracker tracker;
    private LinearLayout registerAcceptLayout;
    private ImageView registerAcceptIcon;
    private TextView viewDetailTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        tracker = ((DXApplication) getApplication()).getTracker(TrackerName.APP_TRACKER);
        tracker.setScreenName("Register");
        tracker.send(new HitBuilders.ScreenViewBuilder().build());
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_register);
        setTitleContent(getString(R.string.title_signup));
        setLeftBtnContent(true, -1);
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        tracker.setScreenName(null);
    }

    private void initView() {
        // 键盘管理
        localInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

        submit = (RelativeLayout) findViewById(R.id.layout_btn_sighup);
        submit.setOnClickListener(this);
        findViewById(R.id.txt_pwd_conf).setOnFocusChangeListener(this);

        //新增勾选框 容器
        registerAcceptLayout = (LinearLayout) findViewById(R.id.register_accept_layout);
        registerAcceptLayout.setOnClickListener(this);
        registerAcceptLayout.setTag(true);
        //勾选框 icon
        registerAcceptIcon = (ImageView) findViewById(R.id.register_accept_icon);

        //View Detail
        viewDetailTv = (TextView) findViewById(R.id.register_accept_view_detail);
        viewDetailTv.setOnClickListener(this);
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.layout_btn_sighup:

                tracker.send(new HitBuilders.EventBuilder("Click", "Submit register").build());
                doSubmit();

                break;
            //点击勾选框
            case R.id.register_accept_layout:
                if (((boolean) registerAcceptLayout.getTag())) {
                    registerAcceptIcon.setImageResource(R.drawable.register_accept_off_icon);
                    registerAcceptLayout.setTag(false);
                } else {
                    registerAcceptIcon.setImageResource(R.drawable.register_accept_on_icon);
                    registerAcceptLayout.setTag(true);

                }
                break;

            //点击View Detail
            case R.id.register_accept_view_detail:
                Intent intent = new Intent(this, InfoChildActivity.class);
                intent.putExtra("settings_item", 5);
                startActivity(intent);
                break;

            default:

                break;
        }
    }

    /**
     * 重置注册
     */
    /*  private void doReset()
      {
          getView(R.id.txt_email).setText(null);
          getView(R.id.txt_username).setText(null);
          //        getView(R.id.txt_firstname).setText(null);
          //        getView(R.id.txt_lastname).setText(null);
          getView(R.id.txt_pwd).setText(null);
          getView(R.id.txt_pwd_conf).setText(null);
      }*/
    private void doGetText() {
//    	//设置清空
//        Logger.i(TAG, "  doGetText");
//        getView(R.id.txt_email).setText(email);
//        // getView(R.id.txt_username).setText(username);
//        getView(R.id.txt_firstname).setText(firstname);
//        getView(R.id.txt_lastname).setText(lastname);
//        getView(R.id.txt_pwd).setText(password);
//        getView(R.id.txt_pwd_conf).setText(passwordConfirm);
        //设置清空
        Logger.i(TAG, "  doGetText");
        getView(R.id.txt_email).setText("");
        // getView(R.id.txt_username).setText(username);
        getView(R.id.txt_firstname).setText("");
        getView(R.id.txt_lastname).setText("");
        getView(R.id.txt_pwd).setText("");
        getView(R.id.txt_pwd_conf).setText("");
        registerAcceptLayout.setTag(false);
        registerAcceptIcon.setImageResource(R.drawable.register_accept_off_icon);
    }

    /**
     * 获取编辑视图对象
     *
     * @param id
     * @return EditText [返回类型说明]
     */
    private EditText getView(int id) {
        return (EditText) findViewById(id);
    }

    /**
     * 提交注册，校验注册信息
     */
    private void doSubmit() {

        // email校验
        EditText emailView = getView(R.id.txt_email);
        email = emailView.getText().toString().trim();
        if (TextUtils.isEmpty(email)) {
            AlertToast.alert(RegisterActivity.this, R.string.user_register_title_email_null, emailView);
            return;
        }
        if (!StringUtil.isEmail(email)) {
            AlertToast.alert(RegisterActivity.this, R.string.user_register_title_email_error, emailView);
            return;
        }
        if (email.length() < Constant.Rule.EMAIL_MIN_LENGTH || email.length() > Constant.Rule.TEXT_MAX_LENGTH) {
            AlertToast.alert(RegisterActivity.this,
                    getString(R.string.user_register_username_validate_length,
                            Constant.Rule.EMAIL_MIN_LENGTH,
                            Constant.Rule.TEXT_MAX_LENGTH),
                    emailView);
            return;
        }
        // username校验
        //        EditText userView = getView(R.id.txt_username);
        //        username = userView.getText().toString().trim();
        //        if (TextUtils.isEmpty(username))
        //        {
        //            AlertToast.alert(RegisterActivity.this, R.string.user_register_title_username_null, userView);
        //            return;
        //        }
        //        if (!ActivityUtil.isUsername(username))
        //        {
        //            AlertToast.alert(RegisterActivity.this, R.string.user_register_title_username_format_error, userView);
        //            return;
        //        }
        //        if (username.length() < Constant.Rule.EMAIL_MIN_LENGTH || username.length() > Constant.Rule.USERNAME_MAX_LENGTH)
        //        {
        //            AlertToast.alert(RegisterActivity.this,
        //                getString(R.string.user_register_username_validate_length,
        //                    Constant.Rule.EMAIL_MIN_LENGTH,
        //                    Constant.Rule.USERNAME_MAX_LENGTH),
        //                userView);
        //            return;
        //        }
        // firstname 校验
        EditText firstnameView = getView(R.id.txt_firstname);
        firstname = firstnameView.getText().toString().trim();
        if (TextUtils.isEmpty(firstname)) {
            AlertToast.alert(RegisterActivity.this, R.string.user_register_title_firstname_null, firstnameView);
            return;
        }
        if (!StringUtil.isFirstnameOrLastname(firstname)) {
            AlertToast.alert(RegisterActivity.this, R.string.user_register_title_firstname_format_error, firstnameView);
            return;
        }
        if (firstname.length() < Constant.Rule.USERNAME_MIN_LENGTH
                || firstname.length() > Constant.Rule.FIRORLASNAME_MAX_LEN) {
            AlertToast.alert(RegisterActivity.this,
                    getString(R.string.user_register_firstname_validate_length,
                            Constant.Rule.USERNAME_MIN_LENGTH,
                            Constant.Rule.FIRORLASNAME_MAX_LEN),
                    firstnameView);
            return;
        }
        // lastname 校验  
        EditText lastnameView = getView(R.id.txt_lastname);
        lastname = lastnameView.getText().toString().trim();
        if (TextUtils.isEmpty(lastname)) {
            AlertToast.alert(RegisterActivity.this, R.string.user_register_title_lastname_null, lastnameView);
            return;
        }
        if (!StringUtil.isFirstnameOrLastname(lastname)) {
            AlertToast.alert(RegisterActivity.this, R.string.user_register_title_lastname_format_error, lastnameView);
            return;
        }
        if (lastname.length() < Constant.Rule.USERNAME_MIN_LENGTH || lastname.length() > Constant.Rule.FIRORLASNAME_MAX_LEN) {
            AlertToast.alert(RegisterActivity.this,
                    getString(R.string.user_register_lastname_validate_length,
                            Constant.Rule.USERNAME_MIN_LENGTH,
                            Constant.Rule.FIRORLASNAME_MAX_LEN),
                    lastnameView);
            return;
        }
        username = firstname + lastname;
        // password校验
        EditText passView = getView(R.id.txt_pwd);
        EditText pass_confView = getView(R.id.txt_pwd_conf);
        password = passView.getText().toString().trim();
        passView.setText(password);
        if (TextUtils.isEmpty(password)) {
            AlertToast.alert(RegisterActivity.this, R.string.user_register_title_password_null, passView);
            return;
        }
        if (password.length() < Constant.Rule.PWD_MIN_LENGTH || password.length() > Constant.Rule.PWD_MAX_LENGTH) {
            AlertToast.alert(RegisterActivity.this,
                    getString(R.string.user_register_pwd_validate_length,
                            Constant.Rule.PWD_MIN_LENGTH,
                            Constant.Rule.PWD_MAX_LENGTH),
                    passView);
            pass_confView.setText(null);
            return;
        }
        // password_conf校验
        passwordConfirm = pass_confView.getText().toString().trim();
        if (!passwordConfirm.equals(password)) {
            AlertToast.alert(RegisterActivity.this, R.string.user_register_title_password_conf_error, pass_confView);
            return;
        }

        //是否同意条款的校验
        if (!((boolean) registerAcceptLayout.getTag())) {
            AlertToast.alert(RegisterActivity.this, R.string.user_register_accept, registerAcceptLayout);

            return;
        }

        //new LoadingRegister().execute();
        AsyncTaskUtil.executeTask(new LoadingRegister());
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!v.isFocused()) {
            IBinder localIBinder = v.getWindowToken();
            localInputMethodManager.hideSoftInputFromWindow(localIBinder, 2);
        }

    }

    protected class LoadingRegister extends AsyncTask<Void, Void, String> {
        @Override
        protected void onPreExecute() {
            submit.setEnabled(false);
//            showWaitingDialog();
            showLoadingLayout(null);
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                String customerid =
                        ProviderFactory.createUserServiceProvider()
                                .register(email, username, firstname, lastname, password);

                if (customerid != null) {
                    Logger.i(TAG, "customerid: " + customerid);
                    UserSessionCfg cfg = com.weipu.common.util.GlobalConfig.getInstance().getUserSessionCfg();
                    cfg.setUsername(username);
                    cfg.setCustomerid(customerid);
                    cfg.setEmail(email);
                }
            } catch (DxException e) {
                return e.getErrCode();
            } catch (Exception e) {
                Logger.e("RegisterActivity", "LoadingRegister", e);
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            if (!isFinishing()) {
//        		 hideWaitingDialog();
        		hideAllLayout();
                 submit.setEnabled(true);
                 if ("0".equals(result))
                 {
                     AlertToast.alert(RegisterActivity.this, getString(R.string.register_register_success));
//                     finish();
                     //直接调用登录的接口
                     AsyncTaskUtil.executeTask(new LoadingUser());
                 }
                 else
                 {
                     AlertToast.alert(RegisterActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                     initView();
                     doGetText();
                 }
        	}
           
        }

    }

    /**
     * 实现登录
     *
     * @author hjd008
     * @version [版本号, 2015-1-14]
     * @see [相关类/方法]
     * @since [产品/模块版本]
     */
    class LoadingUser extends AsyncTask<Void, Void, String> {
        @Override
        protected void onPreExecute() {
            submit.setEnabled(false);
            showLoadingLayout(null);
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                userModel = ProviderFactory.createUserServiceProvider().login(
                        email, password);
            } catch (DxException e) {
                return e.getErrCode();
            } catch (Exception e) {
                Logger.e("LoginActivity", "LoadingUser", e);
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            if (!isFinishing()) {
//				hideWaitingDialog();
                hideAllLayout();
                submit.setEnabled(true);
            }

            if ("0".equals(result)) {
				/*
				 * //Testin 崩溃大师 用户登录名上传
				 * TestinAgent.setUserInfo(userModel.getEmail());
				 */

                GlobalConfig.getInstance().setShoppingCartChange(true);
//				Logger.i(TAG, "获得用户信息：" + userModel.getUsername());
                HashMap<String, String> userConfig = new HashMap<String, String>();

                userConfig.put(
                        ServerConstant.Parameter.PARAMETER_NAME_USER_ACCOUNT,
                        userModel.getUsername());
                userConfig.put(
                        ServerConstant.Parameter.PARAMETER_NAME_USER_EMAIL,
                        userModel.getEmail());
                userConfig.put(
                        ServerConstant.Parameter.PARAMETER_NAME_IS_LOGIN,
                        "true");
                userConfig.put(
                        ServerConstant.Parameter.PARAMETER_USER_CUSTOMERID,
                        userModel.getCustomerid());
                userConfig.put(
                        ServerConstant.Parameter.PARAMETER_NAME_USER_PWD,
                        password);
                userConfig.put(
                        ServerConstant.Parameter.PARAMETER_NAME_TOKEN,
                        userModel.getToken());
                StringUtil.saveConfig(RegisterActivity.this, userConfig);
                //百分点推荐添加用户ID
                BfdAgent.onAddUser(getApplicationContext(), userModel.getCustomerid());

                //设置与极光推送的绑定关系 TODO 设置分组
                setJPushAlias(""+ ActivityUtil.getCustomerID(), null);

                //获取用户的一键过滤设置
                AsyncTaskUtil.executeTask(new GetOneKeyFilterSettingsAsyncTask(RegisterActivity.this, new MyAsyncTaskListenner() {

                    @Override
                    public void onPreTask() {
                    }

                    @Override
                    public void onPostTask(String result, Object obj) {
                        if("0".equals(result)){
                            //获取更新一级目录
                            AsyncTaskUtil.executeTask(new GetTopCategoryAsyncTask(RegisterActivity.this, null));
                        }
                    }
                }));

                //获取用户是否有未读消息
                AsyncTaskUtil.executeTask(new GetIsNotReadAsyncTask(null));
                //更改标记刷新首页的推荐产品数据
                StringUtil.saveConfig("Home_RefreshBFD", "true");
                startByActionType();

            } else {
                AlertToast.alert(RegisterActivity.this,
                        ServerConstant.ReturnCode.MESSAGEMAP.get(result));
            }
        }
    }

    /**
     * 完成activity间跳转
     *
     * @return [参数说明]
     * @return boolean [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    private void startByActionType() {
        Intent intent = new Intent();
        intent.putExtra(
            ServerConstant.Parameter.PARAMETER_NAME_LOGIN_ACTION_TYPE,
            ServerConstant.Parameter.PARAMETER_ACTION_TYPE_LOGIN);
        intent.setClass(this, HomeActivity.class);
        intent.putExtra(HomeActivity.CURRENT_TAB_TAG,
            getString(HomeActivity.titleArray[0]));
        startActivity(intent);
        finish();
    }
}
